package com.fenghongzhang.day008test;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {
    private Button down;
    private Button read;
    private ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        down = (Button) findViewById(R.id.down);
        read = (Button) findViewById(R.id.read);
        img = (ImageView) findViewById(R.id.img);


        //2,版本
        if(Build.VERSION.SDK_INT >=  Build.VERSION_CODES.M){
            //请求权限
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},888);
        }else{

        }
    }

    //3.请求权限的结果.
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 888 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            Toast.makeText(this, "同意", Toast.LENGTH_SHORT).show();
        }else{
            finish();//可选
        }
    }


    //4,下载
    public void down(View view) {
        //下载要在子线程中
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3363295869,2467511306&fm=26&gp=0.jpg");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

//            connection.setReadTimeout(3000);
//            connection.setConnectTimeout(3000);
//            connection.connect();

//            connection.setRequestMethod("POST");
//            connection.setDoOutput(true);
//            connection.setDoInput(true);
//            OutputStream outputStream = connection.getOutputStream();

                    //解决长度为-1的问题
//                    connection.setRequestProperty("Accept-Encoding", "identity");

                    if(connection.getResponseCode() == 200){
                        InputStream inputStream = connection.getInputStream();

                        //直接从流中,转换成一个图片.
//                        final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
//                        runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                img.setImageBitmap(bitmap);
//                            }
//                        });

                        //总大值/当前下载值.
                        int contentLength = connection.getContentLength();//最大值
                        //最大值是 -1

                        //判断sd是否挂载
                        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                            //拿到路径
                            File externalStorageDirectory = Environment.getExternalStorageDirectory();
                            FileOutputStream fileOutputStream = new FileOutputStream(new File(externalStorageDirectory, "xiaomiao.jpg"));

                            int len = 0;


                            byte[] bytes = new byte[1024];
                            while((len = inputStream.read(bytes)) != -1){

//                                int curLen += len;
//
//                               = contentLength/curLen;

                                fileOutputStream.write(bytes,0,len);
                            }
                            fileOutputStream.close();
                        }
                        inputStream.close();
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }

    //5, 读取
    public void read(View view) {
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //storage/emulated/0/
            File externalStorageDirectory = Environment.getExternalStorageDirectory();
            ///storage/emulated/0/xiaomiao.jpg
            File file = new File(externalStorageDirectory, "xiaomiao.jpg");
            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            img.setImageBitmap(bitmap);
        }
    }
}
